//var tmall = require('./tmall');
var express = require('express');
var app = express();
var bodyParser = require('body-parser');
const child_process = require('child_process');

// 创建 application/x-www-form-urlencoded 编码解析
var urlencodedParser = bodyParser.urlencoded({ extended: false });

//设置跨域访问
app.all('*', function(req, res, next) {
    res.header("Access-Control-Allow-Origin", "*");
    res.header("Access-Control-Allow-Headers", "X-Requested-With");
    res.header("Access-Control-Allow-Methods","PUT,POST,GET,DELETE,OPTIONS");
    res.header("X-Powered-By",' 3.2.1')
    res.header("Content-Type", "application/json;charset=utf-8");
    next();
});

app.get('/',function(req,res){
   res.sendFile(__dirname + "/" + "index.htm");
});
app.post('/process_post',urlencodedParser,function(req,res){
    var url = encodeURIComponent(req.body.tmall_url);
    var workerProcess = child_process.exec('/home/nodejsprojects/daigou/node_modules/.bin/slimerjs --headless /home/nodejsprojects/daigou/tmallIndex.js '+url,function(error,stdout,stderr){
        if (error) {
            console.log(error.stack);
            console.log('Error code: '+error.code);
            console.log('Signal received: '+error.signal);
        }
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        res.header("Access-Control-Allow-Origin","*");
        res.end(stdout);
    });
    workerProcess.on('exit', function (code) {
        console.log('子进程已退出，退出码 '+code);
    });
});

app.post('/crawler_entry',urlencodedParser,function(req,res){
    var url = encodeURIComponent(req.body.paste_url);
    var workerProcess = child_process.exec('/home/nodejsprojects/daigou/node_modules/.bin/slimerjs --headless /home/nodejsprojects/daigou/crawler_entry.js '+url,function(error,stdout,stderr){
        if (error) {
            console.log(error.stack);
            console.log('Error code: '+error.code);
            console.log('Signal received: '+error.signal);
        }
        console.log('stdout: ' + stdout);
        console.log('stderr: ' + stderr);
        res.end(stdout);
    });
    workerProcess.on('exit', function (code) {
        console.log('子进程已退出，退出码 '+code);
    });
});

var server = app.listen(8081,function(){
    var host = server.address().address;
    var port = server.address().port;
    console.log("应用实例，访问地址为 http://%s:%s", host, port);
});
